import os

from django import http
from django.shortcuts import render_to_response

from myapp import lunar2ics
from . import forms


def index(request):
    version = os.environ.get('CURRENT_VERSION_ID', '')

    if not request.GET:
        form = forms.Form()
        return render_to_response('lunar2ics/index.html', locals())

    form = forms.Form(data=request.GET)
    if not form.is_valid():
        return render_to_response('lunar2ics/index.html', locals())

    data = form.clean_data
    leapMonth = data.get('leapMonth', False)
    preview = data.get('preview', False)
    response = http.HttpResponse()
    if preview:
        response.headers['Content-Type'] = 'text/plain; charset=UTF-8'
    else:
        response.headers['Content-Type'] = 'text/calendar'
        filename = 'lunar2ics-%02d%02d.ics' % (data['month'], data['day'])
        response.headers['Content-Disposition'] = 'attachment; filename=%s' % filename

    kw = {}
    if leapMonth:
        kw['leapMonthWa'] = int(data.get('leapMonthWa', 0))
    if data['day'] == 30:
        kw['lastDayWa'] = int(data.get('lastDayWa', 0))
    response.write(lunar2ics.lunar2ics(data['month'],
                                       data['day'],
                                       leapMonth,
                                       data['beginYear'],
                                       data['endYear'],
                                       data['summary'],
                                       **kw
                                       ))
    return response